<?php

/*
 * A CLASS TO CREATE CHECK CODE OR VERIFY CHECK CODE
 * @author : MaXiaoHui
 */
class Evebit_Crypt_Hmac{
		private $_func;
		private $_ipad;
		private $_opad;
		private $_key = 'http://www.evebit.com?year=2011';
		public function __construct($key,$method='md5'){
			if(!in_array($method, array("md5","sha1"))){
				die("Unsupported hash function $method");
			}
			if (isset($key)) {
				$this->_key = $key;
			} else {
				$key = $this->_key;
			}
						
			$this->_func = $method;
			
			if (strlen($key) > 64){
				$key = pack("H32",$method($key));
			}
			
			if (strlen($key) < 64) {
				$key = str_pad($key,64,chr(0));
			}

			$this->_ipad = substr($key,0,64) ^ str_repeat(chr(0x36),64);
			$this->_opad = substr($key,0,64) ^ str_repeat(chr(0x5c),64);
			
		}
		
		public function hash($data){
			$func = $this->_func;
			$inner = pack("H32",$func($this->_ipad.$data));
			$digest = $func($this->_opad.$inner);
			return $digest;
		}
		
		
		/*THE RETURN PARAM WILL BELIKE name=evebit&hash=kfej3jrj309979dfd */
		public function createParam($array)
		{
		    $data = '';
		    $ret = array();
		
		    foreach ($array as $key => $value) {
			    $data .=$key.$value;
			    $ret[] = "$key=$value";
		    }
		
		    //$h = new Evebit_Crypt_Hmac($this->_key,"md5");
		    //$hash = $h->hash($data);
		    $hash = $this->hash($data);
		    
		    $ret[] = "hash=$hash";		
		    return join("&amp;", $ret);
		}
		
		
        public function verify_param($array){
		    $data = '';
		    $ret = array();
		
		    $hash = $array['hash'];
		    unset($array['hash']);
		
		    foreach ($array as $key => $value) {
			    $data .=$key.$value;
			    $ret[] ="$key=$value";
		    }
		
		    //$h = new Evebit_Crypt_Hmac($this->_key,"md5");
		    if ($hash != $this->hash($data)){
			    return false;
		    }else {
			    return true;
		    }		
	    }
		
	}